<template>
    <div id="app">
        <!-- 登录页面 -->
        <div class="dh_app-login" v-if="token === ''">
            <el-form label-width="50px" :model="loguser" :rules="logrules" ref="loguser" class="demo-loguser">
                <h3 class="mt1 mb30 tc">员工后台登录页</h3>

                <el-form-item label="" prop="uname">
                    <label slot="label" class=" f24"><i class="iconfont f24 wh icon-yonghu"></i></label>
                    <el-input placeholder="账号" v-model="loguser.uname" clearable></el-input>
                </el-form-item>

                <el-form-item label="" prop="pwd">
                    <label slot="label" class=" f24"><i class="iconfont f24 wh icon-pwd"></i></label>
                    <el-input type="password" placeholder="密码" v-model="loguser.pwd" clearable></el-input>
                </el-form-item>

                <button type="button" class="wh f18" @click="register('loguser')">登录</button>
            </el-form>
        </div>

        <!-- 登录成功的页面布局 -->
        <div class="dh_app-content" v-else>

            <!-- 折叠导航栏 -->
            <el-menu :default-active="activeIndex" router  @select="handleSelect" class="el-menu-vertical-demo" :collapse="isCollapse" :unique-opened="isCollapse" background-color="#000000" text-color="#909399">
                <el-menu-item class="dh_a-c-title b00a i tc" disabled>
                    <i v-if="isCollapse">{{coding.name.substr(0,1)}}</i>
                    <span slot="title">{{coding.name}}</span>
                </el-menu-item>
                <el-menu-item index="/register">
                    <i class="f20 mr5 el-icon-edit-outline"></i>
                    <span slot="title">商标注册</span>
                </el-menu-item>
            </el-menu>

            <!-- 内容的头部 -->
            <div class="dh_a-c-detail">
                <div class="dh_a-c-d-title">
                    <el-radio-group v-model="isCollapse">
                        <el-radio-button :label="fold" @change.native="fold = !fold"><i :class="['iconfont',isCollapse ? 'icon-hanbaobao_shousuo' : 'icon-hanbaobao_shousuo1']"></i></el-radio-button>
                        <!-- <el-radio-button :label="true">收起</el-radio-button> -->
                    </el-radio-group>
                    <!-- 修改密码 -->
                    <div class="dh_a-c-d-amend tc f24">
                        <span>{{succeed}}</span>
                    </div>

                    <div class="dh_acdt-func"> 
                        <!-- <i title="修改密码" @click="amend.state = !amend.state" class="iconfont b00a f24 mr10 icon-xiugaimima"></i> -->
                        <i title="退出登录" @click="exit" class="iconfont ff53 f24 icon-tuichu"></i>
                    </div>
                </div>
                <div class="dh_a-c-d-content"><router-view></router-view></div>
            </div>
        </div>

    </div>
</template>

<script>
const axios = require('axios');
export default {
    components: {},
    data() {
        // 修改密码的两个验证
        var validatePass = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('请输入密码'));
            } else {
            if (this.amend.checkPass !== '') {
                this.$refs.amend.validateField('checkPass');
            }
            callback();
            }
        };
        var validatePass2 = (rule, value, callback) => {
            if (value === '') {
            callback(new Error('请再次输入密码'));
            } else if (value !== this.amend.pass) {
            callback(new Error('两次输入密码不一致!'));
            } else {
            callback();
            }
        };
        return {
            token:'',
            coding: '',
            succeed: '',
            loguser:{uname:'',pwd:''},              //账号密码
            activeIndex: '/',                    //默认的路由页面
            // 登录框的验证信息
            logrules:{
                uname:[{required:true,message:"请输入用户名",trigger:'blur'}],
                pwd:[{required:true,message:"请输入密码",trigger:'blur'}]
            },
            amend:{pass:'',checkpass:'',state:false},                            //重新提交的密码
            // 修改密码的验证
            rules: {
                pass: [
                    { validator: validatePass, trigger: 'blur' }
                ],
                checkpass: [
                    { validator: validatePass2, trigger: 'blur' }
                ]
            },
            isCollapse: true,                       //折叠导航栏的状态
            fold: false,                            //折叠导航栏开关，需要布尔值
            timer: null,                            //定时器
            intervalid: null //定时器置空
        };
    },
    computed: {},
    watch: {
        '$route' () {
			this.handleSelect(this.activeIndex)
		}
    },
    methods: {
        // 登录函数
        register(formName) {
            let that = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let data = {username:that.loguser.uname, password:that.loguser.pwd};
                    let updata = JSON.stringify(data);
                    // console.log(updata)
                    axios({
                        method: 'post',
                        url: '/api/getAuthority/staff',
                        headers: { 'Content-Type': 'application/json' },
                        data: updata
                    })
                    .then( resp=> {
                        console.log(resp)
                        if(resp.data.data !== '没有权限！'){
                            // that.token = resp.data.data;
                            that.refreshing();
                            that.takeserial(data,resp.data.data,true)
                            // that.dingshiqi()
                            this.$message({
                                showClose: true,
                                message: '登录成功',
                                type: 'success',
                                offset: '70'
                            })
                        }else{
                            this.$message({
                                showClose: true,
                                message: '账号或密码输入错误',
                                type: 'error',
                                offset: '70'
                            })
                        }
                    })
                    .catch( err=> {})
                } else {return false;}
            });
        },

        // 拿员工id（号牌）
        async takeserial(data,token,state){
            // console.log('接收值',data,token)
            let that = this
            data.current = 1;
            data.size = 10;
            let updata = JSON.stringify(data);
            // console.log(updata)
            await axios({
                method: 'post',
                url: '/api/staff/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${token}`
                },
                data: updata
            }).then( resp=> {
                // console.log('员工对应的值',resp)
                that.coding = {id:resp.data.data[0].id,name:resp.data.data[0].name,manage:resp.data.data[0].manage}
                sessionStorage.setItem('coding',JSON.stringify(that.coding))
                sessionStorage.setItem('token',JSON.stringify(token))
                sessionStorage.setItem("userdata",JSON.stringify(data))
                that.token = token;
                // console.error(that.timer)
                if(state === true){
                    
                    that.succeed = '欢迎访问员工管理后台！'
                    that.intervalId = setTimeout(() => {
                        //定时器3秒后置空list，取消页面登陆验证失败原因
                        that.succeed = "";
                    }, 3000);
                }
                // 
            }).catch( err=> {})
        },

        // 定时刷星tokeng
        refreshing(){
            // console.log("定时器启动")
            let that = this;
            // // 停止定时器
            let loguser,data,updata
            if(that.timer !== null){
                clearTimeout(that.timer);
            }
            that.timer = setInterval(() => {
                setTimeout(()=>{
                    // console.log("第"+that.timer+"定时器",i++)
                    loguser = JSON.parse(sessionStorage.getItem('userdata'))
                    data = {username:loguser.username, password:loguser.password};
                    updata = JSON.stringify(data);
                    axios({
                        method: 'post',
                        url: '/api/getAuthority/staff',
                        headers: { 'Content-Type': 'application/json' },
                        data: updata
                    }).then( resp=> {
                        // console.log("定时器",resp,that.timer)
                        if(resp.data.data !== '没有权限！'){
                            // sessionStorage.setItem('token',JSON.stringify(resp.data.data))
                            that.takeserial(data,resp.data.data,false)
                        }else{
                            this.$message({
                                showClose: true,
                                message: 'token获取失败！请重新登录',
                                type: 'error',
                                offset: '70'
                            })
                        }
                    }).catch( err=> {})
                },0)
            }, 1700000)
        },

        // 侧边导航栏
        handleOpen(key, keyPath) {
            console.log(key, keyPath);
        },
        handleClose(key, keyPath) {
            console.log(key, keyPath);
        },

        // 退出登录
        exit(){
            this.token = ''
            sessionStorage.removeItem('token')
            sessionStorage.removeItem('userdata')
            sessionStorage.removeItem('coding')
            clearInterval(this.timer)
            this.timer = null
        },

        // 侧边栏函数
        handleSelect(key, keyPath) {
            // console.log(key,keyPath)
			this.activeIndex = key
		},
    },
    created() {
        let that = this;
        that.activeIndex = this.$route.matched[0].path || '/';
        console.log(this.$route.matched)
        // 页面刷新定时器的值丢失，在刷星前就清除掉定时器
        if(that.timer){
            clearInterval(that.timer)
        }else{
            if(sessionStorage.getItem('userdata')){
                this.refreshing()
            }else{return}
        }
        if(sessionStorage.getItem("token")){
			that.token = sessionStorage.getItem("token")
        }else{return}
        
        that.coding = JSON.parse(sessionStorage.getItem('coding'))
    },
    mounted() {},
    beforeCreate() {},
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
}
</script>

<style>
button{
    outline: none;
    border: 0;
}
#app {
    font-family: Helvetica, sans-serif;
    /* text-align: center; */
    height: 100%;
    background: linear-gradient(to right top,#0f30be 10%,#0049d1 30%,#0059ce 50%,#007dc5 70%,#009ec5 90%);
    /* background: url(./assets/bgc.jpg) no-repeat 100% 100%; */
    /* background-size: 100% 100%; */
}
/* 登录框 */
.dh_app-login{
        display: flex;
        /* width: 350px; */
        height: 100%;
    }
    .demo-loguser{
        width: 400px;
        margin: auto;
        padding: 20px 40px;
        border-radius: 5px;
        background: linear-gradient(to bottom right,#fffffff8 -30%, #000000f5 200%);
        box-sizing: border-box;
        box-shadow: 2px 2px 10px #000000;
    }
    .demo-loguser .el-form-item .el-form-item__label{
        background-color: #5c5c5c;
        border-radius: 4px 0 0 4px;
    }
    .el-form-item.is-required:not(.is-no-asterisk)>.el-form-item__label:before{
        content: ''
    }
    .demo-loguser .el-form-item .el-form-item__content .el-input, .demo-loguser .el-form-item .el-form-item__content .el-input input{
        height: 43px;
        border-radius: 0 4px 4px 0;
    }
    .demo-loguser .el-form-item .el-form-item__content .el-form-item__error{
        font-size: 16px;
    }
    .demo-loguser button{
        width: 100%;
        margin-bottom: 10px;
        padding: 10px 0;
        background-color: #434343;
            border-radius: 5px;
    }
    .modify{
        font-size: 13px;
        color: #00b7ff;
    }
    .modify:hover{
        cursor: pointer;
        text-shadow: 0 0 1px #3a3a3a;
    }

/* 登录成功页 */
.dh_app-content{
    display: flex;
    min-height: 100vh;
}
/* 折叠导航栏 */
.el-menu{
    border: 0;
}
.el-menu--collapse{
    text-align: center;
}
.el-menu-vertical-demo:not(.el-menu--collapse) {
    width: 200px;
    min-height: 400px;
    color: transparent;
}
/* 禁用了头部修改的样式 */
.el-menu-item.is-disabled{
    opacity: 1;
    cursor: default;
}
.dh_a-c-title i,.dh_a-c-title span{
    font-size: 24px;
    color: #409eff;
}
/* 导航栏选中状态的固定 */
.dh_app-content .el-menu .el-menu-item.is-active {
    background-color: #272727fa !important;
    color: #64b4ff;
    border-left: 3px solid #64b4ff;
}
.el-menu-item{
    font-size: 16px;
    color: #ffffff;
    border-left: 3px solid #64b4ff00;
}
/* 内容部分布局 */
.dh_a-c-detail{
    width: 100%;
}
.dh_a-c-d-title{
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 55px;
    /* line-height: 50px; */
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e2e2e2;
}
/* 汉堡包图标修改样式 */
.dh_a-c-d-title .el-radio-group .el-radio-button .el-radio-button__inner{
    padding: 7px 15px;
    font-size: 18px;
    color: #0099ff;
    background-color: #ffffff;
    /* border: 0; */
}
/* 修改密码 */
.dh_a-c-d-amend{
    width: calc(100% - 140px);
    /* height: 100%; */
    /* border-right: 1px solid #8b8b8b; */
}
.dh_acda-form span{
    width: 200px;
}
.dh_acda-form .el-form-item{
    margin-bottom: 0;
}
/* 功能按钮的样式 */
.dh_acdt-func .iconfont:hover{
    cursor: pointer;
    /* font-size: 26px; */
    text-shadow: 0 0 2px;
}
/* 路由显示区域 */
.dh_a-c-d-content{
    height: calc(100% - 56px);
    padding: 10px;
    background-color: #f5f5f5fa;
    box-sizing: border-box;
}
</style>